<?php
declare (strict_types=1);

namespace app\exam\service\admin;

use app\common\library\Excel;
use app\common\exception\NotFoundException;
use app\common\model\payment\admin\PaymentOrder;
use app\common\model\payment\admin\PaymentTransaction;
use app\common\model\ProductType;
use app\exam\logic\admin\Order as OrderLogic;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageList;
use think\annotation\Inject;
use think\facade\Request;

/**
 * Class Order
 *
 * @package app\exam\service\admin
 */
class Order
{
    /**
     * @Inject()
     *
     * @var OrderLogic
     */
    protected $orderLogic;

    /**
     * 考试订单
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/5/6
     *
     * @param string $productkey
     * @return \eduline\admin\page\interfaces\think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderList(string $productKey)
    {
        $keys = [
            'examination' => 'exam',
            'special'     => 'special',
            'rollup'      => 'rollup'
        ];

        if (!isset($keys[$productKey])) {
            throw new NotFoundException();
        }
        // 搜索功能
        $map   = $withJoin = [];
        $map[] = ['product_type_id', '=', ProductType::getProductIdByKey($keys[$productKey])];
        Request::has('mhm_id', 'get', true) && $map[] = ['__TABLE__.mhm_id', '=', Request::get('mhm_id/d')];
        Request::has('from', 'get', true) && $map[] = ['__TABLE__.from', '=', Request::get('from/s')];
        Request::has('status', 'get', true) && $map[] = ['pdorder.status', '=', Request::get('status/d')];
        Request::has('payment_type', 'get', true) && $map[] = ['transaction.payment_type', '=', Request::get('payment_type/s')];
        Request::has('phone', 'get', true) && $map[] = ['user.phone', '=', Request::get('phone/s')];
        if (Request::has('time', 'get', true)) {
            $time  = Request::get('time/a');
            $stime = strtotime(date('Y-m-d 00:00:00', strtotime($time[0])));
            $etime = strtotime(date('Y-m-d 00:00:00', strtotime($time[1]))) + 86399;
            $map[] = ['__TABLE__.create_time', 'between', [$stime, $etime]];
        }
        Request::has('order_sub_no', 'get', true) && $map[] = ['__TABLE__.order_sub_no', '=', Request::get('order_sub_no/s')];
        $data        = $this->orderLogic
            ->getList($map)
            ->bindAttr('user', ['phone', 'user_name'])
            ->bindAttr('transaction', ['payment_type_text', 'payment_time'])
            ->hidden(['user', 'transaction', 'pdorder']);
        $is_platform = request()->is_platform;
        // 定义字段
        $keyList = [
            'order_sub_no'      => ListItem::make()->title('订单号'),
            'product_title'     => ListItem::make('custom')->title('名称'),
            'school_name'       => ListItem::make()->title('机构')->visible($is_platform),
            'price'             => ListItem::make('custom')->title('价格'),
            'phone'             => ListItem::make()->title('购买者'),
            'create_time'       => ListItem::make()->title('下单时间'),
            'payment_time'      => ListItem::make()->title('支付时间'),
            'payment_type_text' => ListItem::make()->title('支付方式'),
            'from'              => ListItem::make()->title('订单来源'),
            'status_text'       => ListItem::make()->title('订单状态'),
        ];

        // 支付状态
        $status = app(PaymentOrder::class)->getStatusOptions();
        // 支付方式
        $paymentType = app(PaymentTransaction::class)->getPaymentTypeOptions();
        // 来源
        $from = $this->orderLogic->getFromOptions();

        $searchKey = [
            'mhm_id'       => FormItem::make('searchSchool')->title(false)->visible($is_platform),
            'order_sub_no' => FormItem::make('input')->title(false)->placeholder('订单号'),
            'phone'        => FormItem::make('input')->title(false)->placeholder('购买者手机号')->maxlength(30),
            'status'       => FormItem::make('select')->title(false)->placeholder('订单状态')->options($status),
            'payment_type' => FormItem::make('select')->title(false)->placeholder('支付方式')->options($paymentType),
            'from'         => FormItem::make('select')->title(false)->placeholder('来源')->options($from),
            'time'         => FormItem::make('date')->title(false)->dateType(FormItem::option('DateType', 'DATE_RANGE'))->startPlaceholder('下单开始时间')->endPlaceholder('下单截止时间')->format('yyyy-MM-dd'),
        ];
        // 设置表单
        $list = new PageList;
        // 表单字段
        $list->pageKey   = $keyList;
        $list->searchKey = $searchKey;
        $list->datas     = $data;

        return $list->send();
    }

    /**
     * 订单导出
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-23
     *
     * @return   [type]                         [description]
     */
    public function export(string $productKey)
    {
        $keys = [
            'examination' => 'exam',
            'special'     => 'special',
            'rollup'      => 'rollup'
        ];

        $title = [
            'examination' => '公开考试',
            'special'     => '专项练习',
            'rollup'      => '套卷练习'
        ];

        $withTitle = $productKey . '_title';

        if (!isset($keys[$productKey])) {
            throw new NotFoundException();
        }

        // 搜索功能
        $map[] = ['product_type_id', '=', ProductType::getProductIdByKey($keys[$productKey])];
        Request::has('mhm_id', 'post', true) && $map[] = ['__TABLE__.mhm_id', '=', Request::post('mhm_id/d')];
        Request::has('from', 'post', true) && $map[] = ['__TABLE__.from', '=', Request::post('from/s')];
        Request::has('status', 'post', true) && $map[] = ['pdorder.status', '=', Request::post('status/d')];
        Request::has('payment_type', 'post', true) && $map[] = ['transaction.payment_type', '=', Request::post('payment_type/s')];
        Request::has('phone', 'post', true) && $map[] = ['user.phone', '=', Request::post('phone/s')];
        if (Request::has('time', 'post', true)) {
            $time  = Request::post('time/a');
            $stime = strtotime(date('Y-m-d 00:00:00', strtotime($time[0])));
            $etime = strtotime(date('Y-m-d 00:00:00', strtotime($time[1]))) + 86399;
            $map[] = ['__TABLE__.create_time', 'between', [$stime, $etime]];
        }
        Request::has('order_sub_no', 'post', true) && $map[] = ['__TABLE__.order_sub_no', '=', Request::post('order_sub_no/s')];

        $data = $this->orderLogic
            ->with(['transaction', 'school', 'user', 'pdorder', $withTitle])
            ->withJoin(['user', 'pdorder', 'transaction'], 'LEFT')
            ->where($map)
            ->order('update_time', 'DESC')
            ->select()
            ->bindAttr('user', ['phone', 'user_name'])
            ->bindAttr('transaction', ['payment_type_text', 'payment_time', 'out_trade_no'])
            ->hidden(['user', 'transaction', 'pdorder']);

        $xlsCell = [
            ['order_sub_no', '订单号'],
            ['product_title', '名称'],
            ['school_name', '机构'],
            ['payment', '价格'],
            ['user_name', '购买者'],
            ['create_time', '下单时间'],
            ['payment_time', '支付时间'],
            ['payment_type_text', '支付方式'],
            ['out_trade_no', '商户订单'],
            ['from', '订单来源'],
            ['status_text', '订单状态']
        ];

        $is_platform = request()->is_platform;
        if (!$is_platform) unset($xlsCell['school_name']);

        return Excel::exportExcel($title[$productKey] . '订单', $xlsCell, $data);
    }
}